package org.jetlinks.pro.calculator;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author bestfeng
 * @since 1.9
 */
@Component
public class DefaultValueCalculateBuilder implements ValueCalculateBuilder, BeanPostProcessor {

   private final Map<String, ValueCalculateProvider> providers = new ConcurrentHashMap<>();

    @Override
    public ValueCalculateSupport build(String calculateType,
                                       Map<String, Object> configuration) {
        return getProvider(calculateType)
            .getSupport(configuration);
    }


    private void register(ValueCalculateProvider provider) {
        providers.put(provider.getCalculateType(), provider);
    }

    private ValueCalculateProvider getProvider(String type) {
        if (type == null) {
            throw new IllegalArgumentException("数据计算类型不能为空");
        }
        return Optional
            .ofNullable(providers.get(type))
            .orElseThrow(() -> new IllegalArgumentException("不支持的数据计算类型：" + type));
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ValueCalculateProvider) {
            ValueCalculateProvider provider = (ValueCalculateProvider) bean;
            register(provider);
        }
        return bean;
    }
}
